from flask import Flask, request, jsonify
import base64
import os
from datetime import datetime
from utils import *
from config import Config
from utils.get_card import getCard

app = Flask(__name__)


@app.route('/image_repaired', methods=['POST'])
def app_image_repaired():

    SAVE_PATH = Config.PATH_IMAGE_REPAIRED
    # 获取请求中的base64字符串
    imageBase64 = request.json.get('image')
    if not imageBase64:
        return jsonify({"error": "No image provided"}), 400
    
    image_raw = base64.b64decode(imageBase64, validate=True)
    with open(SAVE_PATH, "wb") as f:
        f.write(image_raw)
        
    image_repaired(SAVE_PATH)
    
    with open(SAVE_PATH, "rb") as image_file:
        encoded_str = base64.b64encode(image_file.read()).decode('utf-8')
        return jsonify({
            "image_repaired": encoded_str
        })


        
@app.route('/super_resolution', methods=['POST'])
def app_super_resolution():

    SAVE_PATH = Config.PATH_IMAGE_SUPER_RESOLUTION
    # 获取请求中的base64字符串
    image_base64 = request.json.get('image')
    if not image_base64:
        return jsonify({"error": "No image provided"}), 400
    
    image_raw = base64.b64decode(image_base64, validate=True)
    with open(SAVE_PATH, "wb") as f:
        f.write(image_raw)
    
    super_resolution(SAVE_PATH)
    
    with open(SAVE_PATH, "rb") as image_file:
        encoded_str = base64.b64encode(image_file.read()).decode('utf-8')
        return jsonify({
            "image_super_resolution": f"{encoded_str}"
        })


@app.route('/image_colorized', methods=['POST'])
def app_image_colorized():
    # 获取请求中的base64字符串
    data_raw = request.json.get('image')
    if not data_raw:
        return jsonify({"error": "No image provided"}), 400
    
    try:
        data_base64 = image_colorized(data_raw)
        if data_base64 is None:
            return jsonify({"error": "Failed to process image"}), 500
        return jsonify({"image_colorized": data_base64}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500
        


@app.route('/generate_video', methods=['POST'])
def app_generate_video():
    SAVE_PATH = Config.PATH_IMAGE_VIDEO
    
    image_base64 = request.json.get('image')
    prompt = request.json.get('prompt')
    if not image_base64 or not prompt:
        return jsonify({"error": "No image_url or prompt provided"}), 400

    if not image_base64:
        return jsonify({"error": "No image provided"}), 400
    
    image_raw = base64.b64decode(image_base64, validate=True)
    with open(SAVE_PATH, "wb") as f:
        f.write(image_raw)
    
    video_url = get_video(SAVE_PATH, prompt)    
    qrcode_base64 = get_qrcode(video_url)
    return jsonify({"video_url": video_url, "qrcode_base64": qrcode_base64}), 200

@app.route('/get_qrcode', methods=['POST'])
def app_get_qrcode():
    url = request.json.get('url')
    if not url:
        return jsonify({"error": "No url provided"}), 400
    
    qrcode_path = get_qrcode(url)
    with open(qrcode_path, "rb") as image_file:
        encoded_str = base64.b64encode(image_file.read()).decode('utf-8')
        return jsonify({"qrcode": encoded_str}), 200


@app.route('/get_card', methods=['POST'])
def app_get_card():
    SAVE_PATH = Config.PATH_IMAGE_CARD
    
    imgBackground = request.json.get('imgBackground')
    imgQrcode = request.json.get('imgQrcode')
    context = request.json.get('context')
    if not imgBackground or not imgQrcode or not context:   
        return jsonify({"error": "No imgBackground or imgQrcode or context provided"}), 400
    
    imgBackground_path = Config.PATH_IMAGE_BACKGROUND
    imgQrcodePath = Config.PATH_IMAGE_QRCODE
    with open(imgBackground_path, "wb") as image_file:
        imgBase64 = base64.b64decode(imgBackground, validate=True)
        image_file.write(imgBase64)
    with open(imgQrcodePath, "wb") as image_file:
        imgBase64 = base64.b64decode(imgQrcode, validate=True)
        image_file.write(imgBase64)

    getCard(imgBackground_path, imgQrcodePath, context)
    with open(SAVE_PATH, "rb") as image_file:
        encoded_str = base64.b64encode(image_file.read()).decode('utf-8')
        return jsonify({"card": encoded_str}), 200

    

if __name__ == '__main__':
    # 注意：在生产环境中使用更安全的方法来运行Flask应用
    app.run(host='0.0.0.0', port=8000, debug=True)